package com.foreveross.crawl.adapter.sub.impl20140402.v3;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest;

import com.foreveross.crawl.adapter.AbstractAdapter;
import com.foreveross.crawl.adapter.PlaneInfoEntityBuilder;
import com.foreveross.crawl.domain.airfreight.AbstractPlaneInfoEntity;
import com.foreveross.crawl.domain.airfreight.CabinEntity;
import com.foreveross.crawl.domain.airfreight.doub.ReturnCabinEntity;
import com.foreveross.crawl.domain.airfreight.single.SinglePlaneInfoEntity;
import com.foreveross.crawl.exception.FlightInfoNotFoundException;
import com.foreveross.taskservice.common.bean.TaskModel;

/**
 * 祥鹏航空
 */
public class LuckyairAdapter extends AbstractAdapter {
	HttpClient client = null;
	/**
	 * 国内单程错误重复次数
	 */
	private final int trysize=3;
	public LuckyairAdapter(TaskModel taskQueue) {
		super(taskQueue);
	}
	
	private   HashMap<String, String> carrierMap=new HashMap<String, String>(){ 
		{
			put("JD", "首都航空");
			put("PN", "西部航空");
			put("GS", "天津航空");
			put("8L", "祥鹏航空");
		}
	};
	
	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		TaskModel taskQueue = new TaskModel();
		taskQueue.setIsInternational(0);
		taskQueue.setFlightDate("2014-11-06");
		taskQueue.setReturnGrabDate("2014-12-08");
		taskQueue.setIsReturn(0);
		// taskQueue.setFromCity("CTU");
		taskQueue.setFromCity("KMG");
		taskQueue.setToCity("PEK");
		LuckyairAdapter apa = new LuckyairAdapter(taskQueue);
		apa.printJson(apa.paraseToVo(apa.fetch(null)), "f:/luckyair.txt");

	}

	@Override
	public List<Object> paraseToVo(Object fetchObject) throws Exception {
		if (fetchObject == null) {
			throw new FlightInfoNotFoundException("无该航班");
		}
		List list = (List) fetchObject;
		if (list.size() == 0) {
			throw new FlightInfoNotFoundException("无该航班");
		}
		return list;
	}

	@Override
	public String getUrl() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object fetch(String url) throws Exception {
		List<AbstractPlaneInfoEntity> result = this.fetchFlight(false, taskQueue.getFromCity(), taskQueue.getToCity(), taskQueue.getFlightDate());
		if (taskQueue.getIsReturn() != 1) {
			PlaneInfoEntityBuilder.buildLimitPrice(result);
			return result;
		}

		List returnResult = this.fetchFlight(true, taskQueue.getToCity(), taskQueue.getFromCity(), taskQueue.getReturnGrabDate());
		if (result == null || result.size() == 0 || returnResult == null || returnResult.size() == 0) {
			return new ArrayList();
		}
		for (AbstractPlaneInfoEntity from : result) {
			PlaneInfoEntityBuilder.getDoubleEntity(from).getReturnPlaneInfos().addAll(returnResult);
		}
		PlaneInfoEntityBuilder.buildRelation(result, returnResult);
		PlaneInfoEntityBuilder.buildLimitPrice(result);
		return result;
	}

	
	
	public List<AbstractPlaneInfoEntity> fetchFlight(Boolean isReturn, String from, String to, String flightDate) throws Exception {
		List<AbstractPlaneInfoEntity> planeInfos = new ArrayList<AbstractPlaneInfoEntity>();
		String data = null;
		String url = "http://www.luckyair.net/flight/flightresult.action?dstCity=" + to + "&flightDate=" + flightDate + "&index=1&orgCity=" + from;
		HttpRequestBase request = new HttpPost(url);
		loadRequestHeader(request);
		data = super.excuteRequest(getHttpClient(), request, true);
		super.appendPageContents(data);
		
		JSONObject j;
		JSONArray flights;
		JSONArray segments;
		JSONArray cabinsArray;		
		j=JSONObject.fromObject(data.trim().replaceAll("^\\(|\\)$", ""));
		flights=j.getJSONArray("flights");
		Set<String> set =new HashSet<String>();
		for(int i=0;i<flights.size();i++){
			JSONObject f=flights.getJSONObject(i);
			segments =f.getJSONArray("segments");
			if(segments.size()>1)
				throw  new Exception("因为没找到哪条航线有中转的……，所以中转的还没做 ");
			JSONObject tran=segments.getJSONObject(0);
			String flightNo=tran.getString("carrier")+tran.getString("flightNo");
			if(set.contains(flightNo))
				continue;
			set.add(flightNo);
			SinglePlaneInfoEntity plane=PlaneInfoEntityBuilder.buildPlaneInfo(taskQueue, tran.getString("carrier"), carrierMap.get(tran.getString("carrier")), carrierMap.get(tran.getString("carrier")),
					null, null, flightNo, null, null, null, tran.getString("aircraftStyle"), 
					null, null, null, null, SinglePlaneInfoEntity.class);
			String startTime=tran.getString("departureTime");
			String endTime=tran.getString("arriveTime");
			if(StringUtils.isNotBlank(startTime))
				plane.setStartTime(this.parse(startTime.replace("T", " "), "yyyy-MM-dd HH:mm:ss"));
			if(StringUtils.isNotBlank(endTime))
				plane.setEndTime(this.parse(endTime.replace("T", " "), "yyyy-MM-dd HH:mm:ss"));
			
			cabinsArray=segments.getJSONObject(0).getJSONArray("cabins");
			Set<CabinEntity> cabins = new HashSet<CabinEntity>();
			for(int k=0;k<cabinsArray.size();k++){
				JSONObject cabinJson=cabinsArray.getJSONObject(k);
				String subCabinName=cabinJson.getString("cabinCode");
				JSONArray productOffers=cabinJson.getJSONArray("productOffers");
				if(!productOffers.isEmpty()){
					for(int key=0;key<productOffers.size();key++){
						JSONObject ob=productOffers.getJSONObject(key);
						JSONObject adultFare=ob.getJSONObject("adultFare");
						Double tax=adultFare.getDouble("airportTax")+adultFare.getDouble("fuelSurcharge");
						CabinEntity cabin=PlaneInfoEntityBuilder.buildCabinInfo(ob.getString("name"), subCabinName, ob.getString("name"),
								tax.toString(), adultFare.getString("farePrice"),
								adultFare.getString("total"), ob.getString("ei"), null, CabinEntity.class);
						cabins.add(cabin);
					}
				}else{
					JSONObject adultFare=cabinJson.getJSONObject("adultFare");
					CabinEntity cabin=PlaneInfoEntityBuilder.buildCabinInfo(null, subCabinName, null,
							null, adultFare.getString("farePrice"),
							adultFare.getString("total"), adultFare.getString("ei"), null, CabinEntity.class);
					cabins.add(cabin);
				}
			}
			plane.setCabins(cabins);
			planeInfos.add(plane);
		}
		try{
			PlaneInfoEntityBuilder.buildLimitPrice(planeInfos);
			}catch(Exception e){
				logger.info("排序错误，请检查数据");
				logger.info(e);
				try{
					logger.info(planeInfos);
				}catch(Exception e1){
					logger.info("打印数据出错");
				}
			}
		
//		ScriptEngineManager sem = new ScriptEngineManager();
//		ScriptEngine engine = sem.getEngineByName("javascript");
//		InputStream is = LuckyairAdapter.class.getClassLoader().getResourceAsStream("js/luckyair.js");
//		engine.eval(IOUtils.toString(is));
//		IOUtils.closeQuietly(is);
//		if (engine instanceof Invocable) {
//			Invocable invoke = (Invocable) engine;
//			String html = (String) invoke.invokeFunction("separateFlight", data, "selectedFlight");
//			validataHtml(html);
//
//			List<List<String>> flightsHtml = RegHtmlUtil.retrieveLinkss(html, this.getRegex1());
//			if (flightsHtml.size() == 0 || flightsHtml.size() == 0) {
//				return new ArrayList();
//			}
//			List<String> cabinName = null;
//			for (List<String> flightHtml : flightsHtml) {
//				AbstractPlaneInfoEntity planeInfo = null;
//				if (isReturn) {
//					planeInfo = PlaneInfoEntityBuilder.buildPlaneInfo(taskQueue, "8L", "祥鹏", flightHtml.get(2), flightHtml.get(4), flightHtml.get(5), flightHtml.get(3), null, null, null, null, ReturnDoublePlaneInfoEntity.class);
//				} else {
//					planeInfo = PlaneInfoEntityBuilder.buildPlaneInfo(taskQueue, "8L", "祥鹏", flightHtml.get(2), flightHtml.get(4), flightHtml.get(5), flightHtml.get(3), null, null, null, null);
//				}
//
//				planeInfos.add(planeInfo);
//				if (cabinName == null) {
//					cabinName = RegHtmlUtil.retrieveLinks(flightHtml.get(1), this.getRegex2(), 1);
//				}
//				List<List<String>> cabinStrs = RegHtmlUtil.retrieveLinkss(flightHtml.get(6), this.getRegex3());
//				Set cabins = new HashSet();
//				for (int i = 0; i < cabinStrs.size(); i++) {
//					List<String> cabinStr = cabinStrs.get(i);
//					this.buildCabin(isReturn, cabins, planeInfo, cabinName.get(i), cabinStr.get(1), cabinName.get(i), PlaneInfoEntityBuilder.getDouble(cabinStr.get(2)));
//				}
//				if (isReturn) {
//					PlaneInfoEntityBuilder.getReturnDoubleEntity(planeInfo).getReturnCabins().addAll(cabins);
//				} else {
//					PlaneInfoEntityBuilder.setCabin(planeInfo, cabins);
//				} 
//			}
//
//		}
		return planeInfos;
	}

	public void buildCabin(boolean isReturn, Set cabinList, AbstractPlaneInfoEntity planeInfo, String cabinType, String subCabinName, String productName, Double price) {
		if (isReturn) {
			ReturnCabinEntity cabinEntity = new ReturnCabinEntity();
			cabinEntity.setCabinType(cabinType);
			cabinEntity.setPlaneInfoEntity(planeInfo);
			cabinEntity.setPrice(price);
			cabinEntity.setProductName(productName);
			cabinEntity.setSubCabinName(subCabinName);
			if(null!=cabinEntity.getTaxesPrice())
				cabinEntity.setOriginalPrice(cabinEntity.getPrice() + cabinEntity.getTaxesPrice());
			cabinList.add(cabinEntity);
		} else {
			CabinEntity cabinEntity = new CabinEntity();
			cabinEntity.setCabinType(cabinType);
			cabinEntity.setPlaneInfoEntity(planeInfo);
			cabinEntity.setPrice(price);
			cabinEntity.setProductName(productName);
			cabinEntity.setSubCabinName(subCabinName);
			if(null!=cabinEntity.getTaxesPrice())
				cabinEntity.setOriginalPrice(cabinEntity.getPrice() + cabinEntity.getTaxesPrice());
			cabinList.add(cabinEntity);
		}
	}

	@Override
	public boolean validateFetch(Object fetchObject) throws Exception {
		return true;
	}

	private void loadRequestHeader(HttpUriRequest request) {
		request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		request.setHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
		request.setHeader("Host", "www.luckyair.net");
		request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		request.setHeader("Referer", "http://www.luckyair.net/flight/searchflight.action");
		request.setHeader("Vary", "Accept-Encoding,User-Agent");
	}
	
	private Date parse(String source, String pattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		try {
			return sdf.parse(source);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

}
